<?php
require_once 'BKPay/Soap/Client.php';
require_once 'BKPay/Constant.php';
require_once 'BKPay/Function.php';

require_once 'modules/transaction/models/Transaction.php';
require_once 'modules/mail/models/Mail.php';
require_once 'modules/user/models/User.php';
require_once 'modules/sms/models/SMS.php';

require_once 'services/classes/MakePaymentRequest.php';
require_once 'services/classes/MakePaymentResponse.php';
require_once 'services/classes/AuthenPaymentRequest.php';
require_once 'services/classes/AuthenPaymentResponse.php';
require_once 'services/classes/RechargePaymentRequest.php';
require_once 'services/classes/RechargePaymentResponse.php';
require_once 'services/classes/TransferPaymentRequest.php';
require_once 'services/classes/TransferPaymentResponse.php';

class transaction_IndexController extends Nine_Controller_Action
{
	public $userId = null;
	
	public function manageAction()
	{
		$this->view->headTitle ( Nine_Language::translate('Transaction Manager'));
			
		$this->_preManage();
		
		if (2 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'merchant';
		}
		else if (3 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'consumer';
		}
		else {
			$this->view->menuId = 'home';
		}
		
		
		$objTransaction = new Models_Transaction();
		
		$config = Nine_Registry::getConfig();
        $numRowPerPage = Nine_Registry::getConfig("defaultNumberRowPerPage");
        $currentPage = $this->_getParam("page",1);
        
		/**
         * Get condition
         */
        $condition = $this->_getParam('condition', false);
        if (false === $condition) {
            $condition = $this->session->contentCondition;
        } else {
            $this->session->contentCondition = $condition;
            $currentPage = 1;
        }
        if (false == $condition) {
            $condition = array();
        }
		
        $allTransactions = $objTransaction->getAllTransaction($condition, 'created_date DESC',
                                                   $numRowPerPage,
                                                   ($currentPage - 1) * $numRowPerPage);
        
        /**
         * Modified
         */                                           
        foreach ($allTransactions as &$transaction) {
        	$transaction['created_date'] = date($config['dateFormat'],$transaction['created_date']);
        	$transaction['id_format'] = str_pad($transaction['transaction_id'], 4,0,STR_PAD_LEFT);
        	$transaction['amount_format'] = number_format($transaction['amount']);
        	if (0 == $transaction['type']) {
        		$transaction['type_name'] = Nine_Language::translate('Payment');
        	}
        	else if (1 == $transaction['type']) {
        		$transaction['type_name'] = Nine_Language::translate('Recharge');
        	}
        	else if (2 == $transaction['type']) {
        		$transaction['type_name'] = Nine_Language::translate('Withdraw');
        	}
        	else if (3 == $transaction['type']) {
        		$transaction['type_name'] = Nine_Language::translate('Transfer');
        	}
        	 
        }                                           
        unset($transaction);
                                                   
        $count = count($objTransaction->getAllTransaction($condition));

        /**
		 * Assign to view
		 */
		$this->setPagination($numRowPerPage, $currentPage, $count);
		$this->view->allTransactions = $allTransactions;
		$this->view->registerMessage = $this->session->registerMessage;
		$this->session->registerMessage = null;
		$this->view->rechargeMessage = $this->session->rechargeMessage;
		$this->session->rechargeMessage = null;
		$this->view->transferMessage = $this->session->transferMessage;
		$this->session->transferMessage = null;
	}
	
	
	public function detailAction()
	{
		$this->view->headTitle (Nine_Language::translate('Transaction Detail'));
		
		$this->_preManage();
		
		if (2 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'merchant';
		}
		else if ( 3 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'consumer';
		}
		else {
			$this->view->menuId = 'home';
		}
		
		$tid = $this->_getParam('tid',false);
		
		if (false == $tid) {
			if (2 == Nine_Registry::getLoggedInGroupId()) {
				$this->_redirect('merchant');
			}
			else if ( 3 == Nine_Registry::getLoggedInGroupId()) {
				$this->_redirect('consumer');
			}
			else {
				$this->_redirect('');
			}
		}
		
		$objTransaction = new Models_Transaction();
		
		$transaction = @$objTransaction->getTransactionWithUser($tid);
		if (null == $transaction) {
			if (2 == Nine_Registry::getLoggedInGroupId()) {
				$this->_redirect('merchant');
			}
			else if ( 3 == Nine_Registry::getLoggedInGroupId()) {
				$this->_redirect('consumer');
			}
			else {
				$this->_redirect('');
			}
		}
		$this->view->transaction = $transaction;
	}
	
	public function authenPaymentAction()
	{
		$this->view->headTitle ( Nine_Language::translate('Authentication Transaction') );
		$this->view->menuId = 'consumer';
		
		$tid = $this->_getParam('tid',false);
		if (false == $tid) {
			$this->_redirect('consumer');
		}
		
		$objTransaction = new Models_Transaction();
		$oldTransaction = @$objTransaction->getTransactionById($tid)->toArray();
		if (null == $oldTransaction) {
			$this->_redirect('consumer');
		}
		
		$data = $this->_getParam('data',false);

		if (false != $data){
			/**
			 * Create connect to service
			 */
			$options = array(
			  'location' => 'https://bkpay.local/transaction/server/api',
			  'uri'      => 'https://bkpay.local/transaction/server/api'
			);
		    $client = new BKPay_Soap_Client(null,$options);
//		    $client->setHttpsCertificate('cert.pem');
		    
		    
		    /**
		     * Make payment
		     */
		    $makePaymentRequest = new MakePaymentRequest();
	    	$makePaymentRequest->actionType = BKPay_Constant::CREATE;

	    	$makePaymentResponse = BKPay_Function::objectToArray($client->makePayment($makePaymentRequest));
			
			/**
		     * Finish payment
		     */
	    	$authenPaymentRequest = new AuthenPaymentRequest();
	    	$authenPaymentRequest->tokenID = $makePaymentResponse['tokenID'];
	    	$authenPaymentRequest->actionType = 'FINISH';
	    	$authenPaymentRequest->activationCode = @$data['activation_code'];
	    	$authenPaymentRequest->transactionID = $tid;
	    	
		    $authenPaymentResponse = BKPay_Function::objectToArray($client->authenPayment($authenPaymentRequest));
		    
		    if (null != @$authenPaymentResponse['timestamp']) {
				$authenPaymentResponse['timestamp'] = date('H:i:s d-m-Y',$authenPaymentResponse['timestamp']);
			}
			
			if (0 ==  @$authenPaymentResponse['ack'] ) {
				$authenPaymentResponse['status'] = Nine_Language::translate("Request is not valid. Please try again !");
			}
			else {
				$authenPaymentResponse['status'] = Nine_Language::translate("Request payment is completed !");
				/**
				 * Send authentication code to email
				 */
				$objMail = new Models_Mail();
				$mailValues = array(
		                    	'full_name'	=>	Nine_Registry::getLoggedInUser()->full_name,
		                    	'timestamp'	=>	$authenPaymentResponse['timestamp'],
		                    	'transactionID'	=>	$authenPaymentResponse['transactionID']
		                    );
		        $objMail->sendHtmlMail('finish_transaction',$mailValues,Nine_Registry::getLoggedInUser()->email);
		        
		        /**
		         * Send authentication code to sms
		         */
		        $objUser = new Models_User();
		        $objSMS = new Models_SMS();
		        $user = $objUser->getUserWithConsumerProfile($this->userId);
		        $newSMS = array(
		        			'telephone_no' => $user['telephone_no'],
		        			'content' => $authenPaymentResponse['paymentInfo'],
		        			'created_date' => time(),
		        			'is_sent' => 0
		        			);
				$objSMS->insert($newSMS);
			}
			
			$this->session->authenPaymentResponse = $authenPaymentResponse;
			$this->_redirect('pay/index/finish-authen-payment');
		}
		else {
			$data = $oldTransaction;
		}
		
		$this->view->data = $data;
	}
	
	public function finishAuthenPaymentAction()
	{
		$this->view->headTitle ( Nine_Language::translate('Finish Transaction') );
		$this->view->menuId = 'consumer';
		
		$this->view->authenPaymentResponse = $this->session->authenPaymentResponse;
		$this->session->authenPaymentResponse = null;
	}
	
	
	
	public function rechargeAction()
	{
		$this->view->headTitle ( Nine_Language::translate('Recharge Money') );
		$this->view->menuId = 'consumer';
		
		$this->_preManage();
		/**
		 * Get data
		 */
		$data = $this->_getParam('data',false);
		$errors = array();
		if (false != $data) {
			
			if (null != $_SESSION['captcha'] && $_SESSION['captcha'] == strtoupper(@$data['captcha'])) {
				if (null != @$data['bkcard_code']) {
					
					/**
					 * Create connect to service
					 */
					$options = array(
					  'location' => 'https://bkpay.local/transaction/server/api',
					  'uri'      => 'https://bkpay.local/transaction/server/api'
					);
				    $client = new BKPay_Soap_Client(null,$options);
				     /**
				     * Make payment
				     */
			     	$makePaymentRequest = new MakePaymentRequest();
		    		$makePaymentRequest->actionType = BKPay_Constant::CREATE;
	
		    		$makePaymentResponse = BKPay_Function::objectToArray($client->makePayment($makePaymentRequest));
					
		    		$rechargePaymentRequest = new RechargePaymentRequest();
		    		$rechargePaymentRequest->actionType = 'RECHARGE';
		    		$rechargePaymentRequest->tokenID = $makePaymentResponse['tokenID'];
		    		$rechargePaymentRequest->userID = $this->userId;
		    		$rechargePaymentRequest->code = $data['bkcard_code'];
		    		
					$rechargePaymentResponse = BKPay_Function::objectToArray($client->rechargePayment($rechargePaymentRequest));
					
					$this->session->rechargeMessage = array(
												'success' => (1 == $rechargePaymentResponse['ack'])?true:false ,
												'message' => $rechargePaymentResponse['paymentInfo'],
												'timestamp' => date('d-m-Y H:i:s',$rechargePaymentResponse['timestamp'])
												);
												
					$this->_redirect('transaction/index/manage');
						
				}
				else {
					$errors = array(
								'message' => Nine_Language::translate("Please enter valid code.")
								);
				}
			}
			else {
				$this->session->__unset('captcha');
				$errors = array('main' => Nine_Language::translate('Code is not match. Please type again'));
			}
			
		}
		
		/**
		 * Assign to view
		 */
		
		$this->view->data = $data;
		$this->view->errors = $errors;
	}
	
	public function withdrawAction()
	{
		$this->view->headTitle ( Nine_Language::translate('Withdraw Money') );
		
		$this->_preManage();
		
		if (2 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'merchant';
		}
		else if ( 3 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'consumer';
		}
		else {
			$this->view->menuId = 'home';
		}
		
	}
	
	public function transferAction()
	{
		$this->view->headTitle ( Nine_Language::translate('Transfer Money') );
		
		$this->_preManage();
		
		if (2 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'merchant';
		}
		else if ( 3 == Nine_Registry::getLoggedInGroupId()) {
			$this->view->menuId = 'consumer';
		}
		else {
			$this->view->menuId = 'home';
		}
		
		$data = $this->_getParam('data',false);
		
		$objUser = new Models_User();
		
		$errors = array();
		if (false != $data) {
			if (null != $_SESSION['captcha'] && $_SESSION['captcha'] == strtoupper(@$data['captcha'])) {
				
				$toUser = @reset($objUser->getByColumns(array('email=?' => $data['to_email']))->toArray());
				
				if (null != $toUser ) {
					/**
					 * Create connect to service
					 */
					$options = array(
					  'location' => 'https://bkpay.local/transaction/server/api',
					  'uri'      => 'https://bkpay.local/transaction/server/api'
					);
				    $client = new BKPay_Soap_Client(null,$options);
	//			    $client->setHttpsCertificate('cert.pem');
				    
				     /**
				     * Make payment
				     */
			     	$makePaymentRequest = new MakePaymentRequest();
		    		$makePaymentRequest->actionType = BKPay_Constant::CREATE;
	
		    		$makePaymentResponse = BKPay_Function::objectToArray($client->makePayment($makePaymentRequest));
					
		    		$transferPaymentRequest = new TransferPaymentRequest();
		    		$transferPaymentRequest->actionType = 'TRANSFER';
		    		$transferPaymentRequest->tokenID = $makePaymentResponse['tokenID'];
		    		$transferPaymentRequest->fromUserID = $this->userId;
		    		$transferPaymentRequest->toUserID = $toUser['user_id'];
		    		$transferPaymentRequest->amount = $data['amount'];
		    		
					$transferPaymentResponse = BKPay_Function::objectToArray($client->transferPayment($transferPaymentRequest));
					
					$this->session->transferMessage = array(
												'success' => (1 == $transferPaymentResponse['ack'])?true:false ,
												'message' => $transferPaymentResponse['paymentInfo'],
												'timestamp' => date('d-m-Y H:i:s',$transferPaymentResponse['timestamp'])
												);
												
					$this->_redirect('transaction/index/manage');
					
				}
				else {
					$errors = array(
								'message' => Nine_Language::translate("User does'nt exist OR invalid email.")
								);
				}
			}
			else {
				$this->session->__unset('captcha');
				$errors = array('main' => Nine_Language::translate('Code is not match. Please type again'));
			}
		}
		
		/**
		 * Assign to view
		 */
		
		$this->view->data = $data;
		$this->view->errors = $errors;
		$this->view->randomNumber = rand(0, 1000000);
	}
	
	private function _preManage()
	{
		/**
		 * Check login
		 */
		$this->_checkLogin();
		
	}
	
	/**
	 * Check login function
	 */
	private function _checkLogin()
	{
		/**
		 * Check login
		 */
		if (false != Nine_Registry::getLoggedInUser()) {
			$this->userId = Nine_Registry::getLoggedInUserId();
		}
		else {
			$this->_redirect ( "access/index/login" );
		}
	}
}